using UnityEngine;
using System.Collections;
using System.Collections.Generic;

public interface CanComponent
{
	bool setActiveComponentIndex (int componentIndex);
}

public abstract class UICan<T> : MonoBehaviour, CanComponent where T : Component
{
	public GameObject targetChildren;
	protected List<T> componentSort;
	protected T activeComponent;
	
	protected void Start ()
	{
		initComponent ();
	}
	
	virtual protected void initComponent ()
	{
		if (targetChildren == null) {
			targetChildren = gameObject;
		}
		
		componentSort = ComponentUtils.getChildrenComponentSort<T> (targetChildren);
		foreach (T component in componentSort) {
			if (isComponentActive (component)) {
				if (activeComponent == null) {
					activeComponent = component;
					
				} else {
					setComponentActive (component, false);
				}
			}
		}
		
		if (activeComponent == null && componentSort.Count > 0) {
			setActiveComponent (componentSort [0]);
		}
	}
	
	public Component getActiveComponent ()
	{
		return activeComponent;
	}
	
	virtual public bool setActiveComponent (T component)
	{
		if (component == activeComponent) {
			return false;
		}
		
		if (activeComponent != null) {
			setComponentActive (activeComponent, false);
		}
		
		setComponentActive (component, true);
		activeComponent = component;
		return true;
	}
	
	virtual public bool setActiveComponentIndex (int componentIndex)
	{
		if (componentSort == null || componentIndex < 0 || componentIndex >= componentSort.Count) {
			return false;
			
		}
		
		return setActiveComponent (componentSort [componentIndex]);
	}
	
	abstract protected bool isComponentActive (T component);
	
	abstract protected void setComponentActive (T component, bool active);
}
